<?php

//Load Master Page
require_once('../shared/layout.php');

//Load Shared Objects & Controls
require_once('../shared/alert.php');

// Load Storage Manager
require_once('../../storage/cloudinary.php');

class Edit extends Layout {

    protected $strTempUploadPath;
    protected $objSetting, $objStorage;
    protected $objAlert, $mctProjectGallery;
    protected $objPreview, $objImage, $objFileUploadDialog, $btnUpload, $btnDelete, $txtDescription;
    protected $intId, $strTempFileName, $strAcceptibleMimeArray, $strUnacceptableMessage;
    protected $btnSave;

    protected function Form_Create() {
        parent::Form_Create();

        $this->objSetting =
                Setting::LoadKeyValueArrayByKeys('portrait_width', 'portrait_height', 'landscape_width', 'landscape_height', 'thumb_por_width', 'thumb_por_height', 'thumb_lan_width', 'thumb_lan_height');

        $this->strContextMenu = __DOCROOT__ . __SUBDIRECTORY__ . '/admin/view/project_gallery/menu/edit.tpl.php';
        
        $this->CssClass = 'form-horizontal';

        $this->objStorage = new CloudinaryStorage();
        $this->objAlert = new Alert($this);

        $this->intId = QApplication::QueryString('intId');
        $this->strAcceptibleMimeArray =
                array(
                    'image/pjpeg' => 'jpg',
                    'image/jpeg' => 'jpg',
                    'image/jpg' => 'jpg',
                    'image/png' => 'png',
                    'image/x-png' => 'png',
                    'image/gif' => 'gif'
        );
        $this->strUnacceptableMessage = QApplication::Translate('Must be a JPG, PNG or GIF');
        $this->strTempUploadPath = __DOCROOT__ . __SUBDIRECTORY__ . '/includes/tmp';

        $this->mctProjectGallery = ProjectGalleryMetaControl::Create($this);

        $this->objFileUploadDialog = new QFileAssetDialog($this, 'objFileUploadDialog_Upload');
        $this->objFileUploadDialog->Width = 400;
        $this->objFileUploadDialog->btnUpload->Text = QApplication::Translate('Accept');
        $this->objFileUploadDialog->btnUpload->CssClass = 'btn btn-primary';
        $this->objFileUploadDialog->btnUpload->AddAction(new QClickEvent(), new QAjaxAction('btnUpload_Click'));
        $this->objFileUploadDialog->btnUpload->AddAction(new QClickEvent(), new QTerminateAction());
        $this->objFileUploadDialog->btnCancel->Text = QApplication::Translate('Cancel');
        $this->objFileUploadDialog->btnCancel->CssClass = 'btn';
        $this->objFileUploadDialog->AddJavascriptFile('../../../admin/content/plugins/bootstrap-filestyle/src/bootstrap-filestyle.js');
        
        $this->objPreview = new QImageControl($this);
        $this->objPreview->Name = QApplication::Translate('Image');
        $this->objPreview->ImagePath = __DOCROOT__ . '/admin/content/images/sample.gif';
        $this->objPreview->Width = 360;
        $this->objPreview->Height = 270;
        $this->objPreview->Required = true;
        $this->objPreview->Quality = 80;
        $this->objPreview->ScaleCanvasDown = true;
        
        $this->objImage = new QImageControl($this);
        $this->objImage->Quality = 80;
        $this->objImage->ScaleCanvasDown = true;

        $this->btnUpload = new QButton($this);
        $this->btnUpload->Text = '<i class="icon-cloud-upload"></i> ' . QApplication::Translate('Upload');
        $this->btnUpload->AddAction(new QClickEvent(), new QShowDialogBox($this->objFileUploadDialog));
        $this->btnUpload->AddAction(new QClickEvent(), new QTerminateAction());

        $this->btnDelete = new QButton($this);
        $this->btnDelete->Text = '<i class="icon-remove"></i> ' . QApplication::Translate('Delete');
        $this->btnDelete->Visible = false;
        $this->btnDelete->AddAction(new QClickEvent(), new QAjaxAction('btnDelete_Click'));
        $this->btnDelete->AddAction(new QClickEvent(), new QTerminateAction());

        $this->txtDescription = $this->mctProjectGallery->txtDescription_Create();

        $this->btnSave = new QButton($this);
        $this->btnSave->Text = QApplication::Translate('Save Changes');
        $this->btnSave->PrimaryButton = $this->btnSave->CausesValidation = true;
        $this->btnSave->AddAction(new QClickEvent(), new QToggleEnableAction($this->btnSave));
        $this->btnSave->AddAction(new QClickEvent(), new QAjaxAction('btnSave_Click'));
        $this->btnSave->AddJavascriptFile('../../../admin/content/js/project_gallery/edit.js');
    }

    protected function Form_PreRender() {
        parent::Form_PreRender();

        QApplication::ExecuteJavaScript('Edit.init();');
    }
    
    protected function Form_Validate() {
       $blnToReturn = parent::Form_Validate();

        if ($blnToReturn)
            $this->btnSave->Enabled = true;

        return $blnToReturn;
    }

    public function objFileUploadDialog_Upload() {
        try {
            // File Not Uploaded
            if (!file_exists($this->objFileUploadDialog->flcFileAsset->File) || !$this->objFileUploadDialog->flcFileAsset->Size) {
                $this->objFileUploadDialog->ShowError($this->strUnacceptableMessage);

                // File Has Incorrect MIME Type (only if an acceptiblemimearray is setup)
            } else if (is_array($this->strAcceptibleMimeArray) && (!array_key_exists($this->objFileUploadDialog->flcFileAsset->Type, $this->strAcceptibleMimeArray))) {
                $this->objFileUploadDialog->ShowError($this->strUnacceptableMessage);

                // File Successfully Uploaded
            } else {

                // Setup Filename, Base Filename and Extension
                $strFilename = $this->objFileUploadDialog->flcFileAsset->FileName;
                $intPosition = strrpos($strFilename, '.');

                if (is_array($this->strAcceptibleMimeArray) && array_key_exists($this->objFileUploadDialog->flcFileAsset->Type, $this->strAcceptibleMimeArray)) {
                    $strExtension = $this->strAcceptibleMimeArray[$this->objFileUploadDialog->flcFileAsset->Type];
                } else {
                    if ($intPosition)
                        $strExtension = substr($strFilename, $intPosition + 1);
                    else
                        $strExtension = null;
                }

                $strBaseFilename = substr($strFilename, 0, $intPosition);
                $strExtension = strtolower($strExtension);

                // Save the File in a slightly more permanent temporary location
                $this->strTempFileName = basename($this->objFileUploadDialog->flcFileAsset->File) . rand(1000, 9999) . '.' . $strExtension;
                $strTempFilePath = $this->strTempUploadPath . DIRECTORY_SEPARATOR . $this->strTempFileName;
                copy($this->objFileUploadDialog->flcFileAsset->File, $strTempFilePath);

                // Hide the Dialog Box
                $this->objFileUploadDialog->HideDialogBox();

                //Refresh Preview
                list($width, $height) = getimagesize($strTempFilePath);
                $fltRatio = $width / $height;

                if ($fltRatio == 0 || $fltRatio > 1) {
                    // Landscape
                    $width = 360;
                    $height = 270;
                } else {
                    // Portrait
                    $width = 270;
                    $height = 360;
                }

                // Refresh Preview
                $this->objPreview->ImagePath = $strTempFilePath;
                $this->objPreview->Width = $width;
                $this->objPreview->Height = $height;
                $this->objPreview->Refresh();

                $this->btnUpload->Visible = false;
                $this->btnDelete->Visible = true;
            }
        } catch (QCallerException $objExc) {
            $objExc->IncrementOffset();
            $this->objAlert->Error(QApplication::Translate('Ooops!'), $objExc->getMessage());
        }
    }

    protected function btnDelete_Click($strFormId, $strControlId, $strParameter) {
        try {
            $strTempFilePath = $this->strTempUploadPath . DIRECTORY_SEPARATOR . $this->strTempFileName;

            if (file_exists($strTempFilePath))
                unlink($strTempFilePath);

            $this->objPreview->ImagePath = __DOCROOT__ . '/admin/content/images/sample.gif';
            $this->objPreview->Width = 360;
            $this->objPreview->Height = 270;
            $this->objPreview->Refresh();

            $this->btnUpload->Visible = true;
            $this->btnDelete->Visible = false;
        } catch (QCallerException $objExc) {
            $objExc->IncrementOffset();
            $this->objAlert->Error(QApplication::Translate('Ooops!'), $objExc->getMessage());
        }
    }

    protected function btnSave_Click($strFormId, $strControlId, $strParameter) {
        try {

            $strTempFilePath = $this->strTempUploadPath . DIRECTORY_SEPARATOR . $this->strTempFileName;

            if (!file_exists($strTempFilePath)) {
                $this->objAlert->Error(QApplication::Translate('Ooops!'), QApplication::Translate('Image No Exists!'));
                return;
            }

            list($width, $height) = getimagesize($strTempFilePath);
            $fltRatio = $width / $height;

            if ($fltRatio == 0 || $fltRatio > 1) {
                // Landscape
                $width = $this->objSetting['landscape_width'];
                $height = $this->objSetting['landscape_height'];
            } else {
                // Portrait
                $width = $this->objSetting['portrait_width'];
                $height = $this->objSetting['portrait_height'];
            }

            $this->objImage->ImagePath = $this->objPreview->ImagePath;
            $this->objImage->Width = $width;
            $this->objImage->Height = $height;
            $this->objImage->RenderImage($strTempFilePath);

            $result = $this->objStorage->Upload($strTempFilePath, array());

            $this->mctProjectGallery->ProjectGallery->ProjectId = $this->intId;
            $this->mctProjectGallery->ProjectGallery->Internal = $result['public_id'];
            $this->mctProjectGallery->ProjectGallery->Url = $result['url'];
            $this->mctProjectGallery->ProjectGallery->SecureUrl = $result['secure_url'];

            $this->mctProjectGallery->ProjectGallery->ThumbUrl =
                    sprintf('%s.%s', $this->objStorage->Get($result['public_id'], array(crop => 'thumb', width => 260, height => 180, quality => 60)), $result['format']);

            $this->mctProjectGallery->ProjectGallery->Width = $result['width'];
            $this->mctProjectGallery->ProjectGallery->Height = $result['height'];
            $this->mctProjectGallery->ProjectGallery->Format = $result['format'];
            $this->mctProjectGallery->ProjectGallery->Size = $result['bytes'];
            $this->mctProjectGallery->ProjectGallery->LogUser = $this->objCurrentUser->Username;
            $this->mctProjectGallery->ProjectGallery->LogInsert = QDateTime::Now();

            $this->mctProjectGallery->SaveProjectGallery();
            
            $this->objAlert->Success(QApplication::Translate('Success'), QApplication::Translate('Project Gallery Saved Successful !'));
        } catch (QCallerException $objExc) {
            $objExc->IncrementOffset();
            $this->objAlert->Error(QApplication::Translate('Ooops!'), $objExc->getMessage());
        }
        
        $this->btnSave->Enabled = true;
    }

}

Edit::Run('Edit', __DOCROOT__ . __SUBDIRECTORY__ . '/admin/view/project_gallery/edit.tpl.php');
?>